package org.example.cloudapply.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.cloudapply.config.WechatConfig;
import org.example.cloudapply.dto.WxLoginDTO;
import org.example.cloudapply.entity.User;
import org.example.cloudapply.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

@Service
public class WechatAuthService {

    private final RestTemplate restTemplate;
    private final WechatConfig wechatConfig;
    private final UserRepository userRepository;

    @Autowired
    public WechatAuthService(RestTemplate restTemplate, WechatConfig wechatConfig, UserRepository userRepository) {
        this.restTemplate = restTemplate;
        this.wechatConfig = wechatConfig;
        this.userRepository = userRepository;
    }

    public String wechatLogin(WxLoginDTO dto) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", wechatConfig.getAppid());
        params.put("secret", wechatConfig.getSecret());
        params.put("js_code", dto.getCode());
        params.put("grant_type", "authorization_code");

        try {
            // 修改为获取原始响应字符串
            ResponseEntity<String> response = restTemplate.getForEntity(
                    wechatConfig.getAuthUrl() + "?appid={appid}&secret={secret}&js_code={js_code}&grant_type={grant_type}",
                    String.class,
                    params
            );

            String responseBody = response.getBody();
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> result = mapper.readValue(responseBody, new TypeReference<Map<String, Object>>() {});

            if (result.containsKey("errcode")) {
                throw new RuntimeException("微信登录失败: " + result.get("errmsg"));
            }

            String openid = (String) result.get("openid");
            // 检查用户是否存在
            User user = userRepository.findByOpenid(openid);
            //if (user == null) {
                //user = new User();
                //user.setOpenid(openid);
                //userRepository.insert(user);
            //}
            return openid;
        } catch (JsonProcessingException e) {
            throw new RuntimeException("微信响应解析失败");
        } catch (RestClientException e) {
            throw new RuntimeException("微信接口调用失败");
        }
    }
}
